/*
 * Copyright (C) 2013 Michael
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.jm.xporta;

import com.jm.xporta.plugin.XPort;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @created Feb 12, 2013
 * @author Michael L.R. Marques
 */
public class XPorta extends javax.swing.JFrame implements XPort {

    /**
     *
     */
    private ResultSet results;
    /**
     *
     */
    private File output;
    /**
     *
     */
    private boolean done;

    /**
     * Creates new form XPorta
     */
    public XPorta() {
        super();
        initComponents();
        this.panelBackground.setImage(new File("./images/optionslogo.png"));
    }

    /**
     *
     * @param results
     */
    @Override
    public void initialize(ResultSet results) throws XPortException {
        this.results = results;
        try {
            this.results.beforeFirst();
        } catch (SQLException sqle) {
            throw new XPortException(sqle);
        }
    }

    /**
     *
     * @return
     */
    @Override
    public String getName() {
        return "Basic XPorta Plugin";
    }

    /**
     *
     * @return
     */
    @Override
    public String getDescription() {
        return "Basic plugin component that can be inherited, for ease of use.";
    }

    /**
     *
     * @return
     */
    @Override
    public ResultSet getData() {
        return this.results;
    }

    /**
     *
     * @param output
     */
    @Override
    public void setOutput(Object output) throws XPortException {
        if (!(output instanceof File)) {
            throw new XPortException("Output must be of a file type");
        }
        this.output = (File) output;
    }

    /**
     *
     * @return
     */
    @Override
    public Object getOutput() {
        return this.output;
    }

    /**
     *
     * @return
     */
    @Override
    public FileFilter[] getFileFilters() {
        return new FileFilter[0];
    }

    /**
     *
     * @param max
     */
    @Override
    public void setProgressMaximum(int max) {
        this.progress.setMaximum(max);
    }

    /**
     *
     * @param min
     */
    @Override
    public void setProgressMinimum(int min) {
        this.progress.setMinimum(min);
    }

    /**
     *
     * @param value
     */
    @Override
    public void setProgressValue(int value) {
        this.progress.setValue(value);
    }

    /**
     *
     * @return
     */
    @Override
    public int getProgressValue() {
        return this.progress.getValue();
    }

    /**
     * This is where the work is done
     */
    @Override
    public void export() throws XPortException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * 
     * @param done 
     */
    @Override
    public void done(boolean done) {
        this.done = done;
    }

    /**
     *
     * @return
     */
    @Override
    public boolean isDone() {
        return this.done;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelBackground = new com.jm.commons.components.panel.ImagePanel();
        progress = new javax.swing.JProgressBar();
        btnExport = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        chbOpenOnComplete = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("XPorting...");
        setAlwaysOnTop(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        panelBackground.setImage(null);

        progress.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                progressStateChanged(evt);
            }
        });

        btnExport.setText("Export");
        btnExport.setToolTipText("");
        btnExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        chbOpenOnComplete.setText("Open On Complete");
        chbOpenOnComplete.setOpaque(false);

        javax.swing.GroupLayout panelBackgroundLayout = new javax.swing.GroupLayout(panelBackground);
        panelBackground.setLayout(panelBackgroundLayout);
        panelBackgroundLayout.setHorizontalGroup(
            panelBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBackgroundLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progress, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addGroup(panelBackgroundLayout.createSequentialGroup()
                        .addComponent(chbOpenOnComplete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExport)))
                .addContainerGap())
        );
        panelBackgroundLayout.setVerticalGroup(
            panelBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBackgroundLayout.createSequentialGroup()
                .addGap(92, 92, 92)
                .addComponent(progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExport)
                    .addComponent(btnCancel)
                    .addComponent(chbOpenOnComplete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelBackground, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelBackground, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed
        // Open the file chooser
        try {
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Save File...");
            fileChooser.setCurrentDirectory(new java.io.File("./"));
            fileChooser.setAcceptAllFileFilterUsed(false);
            fileChooser.setMultiSelectionEnabled(false);
            // Add a file filter
            for (FileFilter filter : getFileFilters()) {
                fileChooser.addChoosableFileFilter(filter);
            }
            // Show file chooser option is approved
            if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
                setOutput(fileChooser.getSelectedFile());
                try {
                    export();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Runtime.getRuntime().exec(fileChooser.getSelectedFile().getAbsolutePath());
                            } catch (IOException ioe) {
                                JOptionPane.showMessageDialog(null, ioe.getMessage(), "Open Xported File", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }).start();
                    setVisible(false);
                    dispose();
                } catch (XPortException xpe) {
                    JOptionPane.showMessageDialog(this, xpe.getMessage(), "XPort Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (XPortException | HeadlessException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "XPort Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnExportActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        setVisible(false);
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        setVisible(false);
        dispose();
    }//GEN-LAST:event_formWindowClosing

    private void progressStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_progressStateChanged
        ((JProgressBar) evt.getSource()).update(((JProgressBar) evt.getSource()).getGraphics());
    }//GEN-LAST:event_progressStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnExport;
    private javax.swing.JCheckBox chbOpenOnComplete;
    private com.jm.commons.components.panel.ImagePanel panelBackground;
    private javax.swing.JProgressBar progress;
    // End of variables declaration//GEN-END:variables
}
